package com.mrd.gtimp.business.service;

import com.mrd.base.BaseBiz;
import com.mrd.exception.SaveException;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.FundAjustment;
import com.mrd.gtimp.business.entity.FundFlow;
import com.mrd.gtimp.business.entity.YxtPayParams;
import com.mrd.gtimp.business.repository.FundAjustmentDao;
import com.mrd.gtimp.v2.fund.FundIETypeEnum;
import com.mrd.gtimp.v2.fund.FundPayTypeEnum;
import com.mrd.gtimp.v2.fund.FundStateEnum;
import com.mrd.payClient.PayClient;
import com.mrd.payClient.message.PayMessage;
import com.mrd.payClient.utils.MD5Util;
import com.mrd.spring.repository.BaseRepository;
import com.mrd.util.LoginUtil;
import com.mrd.util.StringUtils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */
@Service
public class FundAjustmentBiz extends BaseBiz<FundAjustment> {

    @Resource
    // 该处指定注入BaseRepository的dao对象
    @Qualifier("fundAjustmentDao")
    public void setBaseRepository(BaseRepository<FundAjustment, String> baseRepository) {
        super.baseRepository = baseRepository;
    }

    @Resource
    @Qualifier("fundFlowBiz")
    private FundFlowBiz fundFlowBiz;

    @Resource
    private PaymentABCBiz paymentABCBiz;

    @Resource
    private FundAccountBiz fundAccountBiz;

    @Resource
    private FundAjustmentDao fundAjustmentDao;

    @Autowired
    private PaymentPlatformBiz  paymentPlatformBiz;

    Logger log = Logger.getLogger(FundAjustmentBiz.class);


    public void reviewPass(FundAjustment fundAjustment) {
        User reviewer = fundAjustment.getReviewer();
        log.error("reviewPass start:" + fundAjustment.getId());
        try {
            String reviewShuiDan = fundAjustment.getReviewShuiDan();
            fundAjustment = baseRepository.findEntityById(fundAjustment.getId());

            FundFlow flow = fundFlowBiz.addFlow(fundAjustment.getOwner(), fundAjustment.getAmount(), FundIETypeEnum.RECHARGE, fundAjustment.getBid());

            baseRepository.updateBySql("UPDATE T_BIZ_FUND_AJUSTMENT SET REVIEW_DATE=TO_DATE('"
                    + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                    + "','YYYY-MM-DD HH24:MI:SS'),REVIEW_USER_ID='" + reviewer.getId()
                    + "', STATE='SUCCESS', FUNDFLOW_ID='" + flow.getId() + "',REVIEW_SHUIDAN_NO='"
                    + (reviewShuiDan != null ? reviewShuiDan : "") + "' WHERE ID='"
                    + fundAjustment.getId() + "'");
            log.error("reviewPass success:" + flow.getId());
        } catch (SaveException e) {
            e.printStackTrace();
            log.error("reviewPass fail:" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("reviewPass fail:" + e.getMessage());
        }
    }


    public void onlinePaySuccess(FundAjustment fundAjustment) {
        log.error("onlinePaySuccess start:" + fundAjustment.getId());
        try {
            FundFlow flow = fundFlowBiz
                    .addFlow(fundAjustment.getOwner(), fundAjustment.getAmount(), FundIETypeEnum.ONLINE_RECHARGE, fundAjustment
                            .getBid());
            fundAjustment.setState(FundStateEnum.SUCCESS.toString());
            baseRepository.updateBySql("UPDATE T_BIZ_FUND_AJUSTMENT SET REVIEW_DATE=TO_DATE('"
                    + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
                    + "','YYYY-MM-DD HH24:MI:SS'), STATE='SUCCESS', FUNDFLOW_ID='" + flow.getId()
                    + "' WHERE ID='" + fundAjustment.getId() + "'");
            log.error("onlinePaySuccess success:" + flow.getId());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("onlinePaySuccess fail:" + e.getMessage());
        }
    }

    /**
     * 获取支付平台交易订单
     * @param payChannel 支付渠道 0支付宝，1微信
     * @param userKey 接入支付平台的key
     * @param orderNo 一线通交易订单号
     * @param totalAmount 交易金额 单位：元
     */
    @Transactional
    public PayMessage getPayPlatformPayMessage(String payChannel, String userKey, String orderNo, String totalAmount){
        FundAjustment fundAjustment = fundAjustmentDao.findByBillNo(orderNo);
        PayMessage payMessage = null;
        if(fundAjustment != null){
            updateAjustment(fundAjustment, orderNo, payChannel, totalAmount); //更新交易订单
            payMessage = getPayMessageFormPayPlatform(payChannel, userKey, orderNo, totalAmount);
            //todo 不予支付平台进行交易，拿到已经保存的待支付信息
        }else{
            newAndSaveAjustment(orderNo, payChannel, totalAmount); //新增交易订单
            payMessage = getPayMessageFormPayPlatform(payChannel, userKey, orderNo, totalAmount);
        }
        payMessage.setOutTradeNo(orderNo);

        return payMessage;
    }

    /**
     * 获取支付平台在线交易地址
     * @param userKey 接入支付平台的key
     * @param orderNo 一线通交易订单号
     * @param totalAmount 交易金额 单位：元
     */
    @Transactional
    public String getPayPlatformOnlinePayUrl(String userKey, String orderNo, String totalAmount){
        FundAjustment fundAjustment = fundAjustmentDao.findByBillNo(orderNo);
        String payChannel = "2"; //支付宝
        if(fundAjustment != null){
            updateAjustment(fundAjustment, orderNo, payChannel, totalAmount); //更新交易订单
        }else{
            newAndSaveAjustment(orderNo, payChannel, totalAmount); //新增交易订单
        }

        return paymentPlatformBiz.getOnlineAliPayUrl(orderNo, totalAmount, userKey);
    }

    /**
     * 从支付平台获取获取交易信息
     * @param payChannel 支付渠道 0支付宝，1微信
     * @param userKey 接入支付平台的key
     * @param orderNo 一线通交易订单号
     * @param totalAmount 交易金额 单位：元
     */
    private PayMessage getPayMessageFormPayPlatform(String payChannel, String userKey, String orderNo, String totalAmount){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(new Date());
        User loginUser = LoginUtil.getLoginUser();

        YxtPayParams params = new YxtPayParams();
        params.setBody(time+"-"+loginUser.getCompany().getName()+"-预付款:"+totalAmount+"元");
        params.setPayChannel(payChannel);
        params.setOutTradeNo(orderNo);
        params.setSubject("预付款单号:" + orderNo);
        long _totalAmount = (long) (Float.parseFloat(totalAmount)*100);
        params.setTotalAmount(String.valueOf(_totalAmount));
        params.setTradeType("NATIVE");
        params.setUserKey(userKey);
        params.setSign(MD5Util.getMD5(params.getUserKey() + params.getOutTradeNo()));

        params.setTimeStart(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(new Date()) + ":" + params);
        PayClient payClient = new PayClient();
        PayMessage payMessage = payClient.play(params);

        System.out.println(sdf.format(new Date()) + ":" + payMessage);
        return payMessage;
    }

    public void newAndSaveAjustment(String outTradeNo, String payCannel,String totalAmount){
        FundAjustment fundAjustment = new FundAjustment();
        fundAjustment.setId(null);
        fundAjustment.setOwner(LoginUtil.getLoginUser().getCompany());
        fundAjustment.setRegDate(new Date());
        fundAjustment.setRegistrant(LoginUtil.getLoginUser());
        fundAjustment.setBillNo(outTradeNo);
        fundAjustment.setAmount(Double.parseDouble(totalAmount));
        fundAjustment.setState(FundStateEnum.TEMP.toString());
        if(payCannel.equalsIgnoreCase("1")){
            fundAjustment.setFundPayType(FundPayTypeEnum.WechatPay.toString());
        }else if(payCannel.equalsIgnoreCase("2")){
            fundAjustment.setFundPayType(FundPayTypeEnum.Alipay.toString());
        }
        //先填payType 在填bid
        fundAjustment.setBid(fundAjustment.generateBid());
        baseRepository.save(fundAjustment);
    }


    /**
     * 根据支付订单号更新支付记录的支付渠道以及金额
     * @param outTradeNo
     * @param payCannel
     * @param totalAmount
     * @throws SaveException
     */
    public void updateAjustment(FundAjustment fundAjustment, String outTradeNo, String payCannel,String totalAmount) {
        fundAjustment.setOwner(LoginUtil.getLoginUser().getCompany());
        fundAjustment.setRegDate(new Date());
        fundAjustment.setRegistrant(LoginUtil.getLoginUser());
        fundAjustment.setAmount(Double.parseDouble(totalAmount));
        fundAjustment.setBillNo(outTradeNo);
        fundAjustment.setState(FundStateEnum.TEMP.toString());
        if(payCannel.equalsIgnoreCase("1")){
            fundAjustment.setFundPayType(FundPayTypeEnum.WechatPay.toString());
        }else if(payCannel.equalsIgnoreCase("2")){
            fundAjustment.setFundPayType(FundPayTypeEnum.Alipay.toString());
        }
        baseRepository.save(fundAjustment);
    }
}
